package com.hongji.lms5xxcommunicator.entity;

import com.hongji.lms5xxcommunicator.grid.core.GridSpec;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.stereotype.Component;

/** 保存“最近一帧”以及按 key 的快照缓存（P0：很轻量的本地内存缓存） */
@Component
public class SnapshotCache {

    private final AtomicReference<Object> last = new AtomicReference<>();
    private final Map<String, Object> map = new ConcurrentHashMap<>();

    public void update(Object dto) { last.set(dto); }
    public Object latest() { return last.get(); }

    public void put(String key, Object dto) { if (key != null && dto != null) map.put(key, dto); }
    @SuppressWarnings("unchecked")
    public <T> T get(String key) { return (T) map.get(key); }

    /** 生成一个稳定的 cacheKey，包含 spec 与查询窗口 */
    public static String keyOf(GridSpec spec, com.hongji.lms5xxcommunicator.entity.GridBootstrapParam p) {
        StringBuilder sb = new StringBuilder(128);
        sb.append("x0=").append(spec.x0).append(",x1=").append(spec.x1)
                .append(",y0=").append(spec.y0).append(",y1=").append(spec.y1)
                .append(",dx=").append(spec.dx).append(",dy=").append(spec.dy);
        if (p != null) {
            if (p.getTFrom() != null) sb.append(",tFrom=").append(p.getTFrom());
            if (p.getTTo()   != null) sb.append(",tTo=").append(p.getTTo());
        }
        return sb.toString();
    }
}
